package vt.ece4564.phonetracker;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class SMSReceiver extends BroadcastReceiver
{
	private String m_secretPhrase;
	private GPSMonitor m_GPSMonitor;
	
	public SMSReceiver(String secretPhrase, GPSMonitor g)
	{
		m_secretPhrase = secretPhrase;
		m_GPSMonitor = g;
	}
	
    @Override
    public void onReceive(Context context, Intent intent)
    {
    	if (m_secretPhrase.equals("dne"))
    		return;
        Bundle bundle = intent.getExtras();
        SmsMessage[] recievedMsgs = null;
        String str = "";
        if (bundle != null)
        {
            Object[] pdus = (Object[]) bundle.get("pdus");
            recievedMsgs = new SmsMessage[pdus.length];
            for (int i=0; i < pdus.length; i++)
            {
            	recievedMsgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
            	String sender = recievedMsgs[i].getOriginatingAddress();
            	String message = recievedMsgs[i].getMessageBody().toString();
                
                if (m_secretPhrase.equals(message))
                {
                	Message msg = Message.obtain();
                	msg.obj = sender;
                	m_GPSMonitor.Handler.sendMessage(msg);
                }
                Log.d("TextMessageMonitor", "Received a text: "+ message);
            }
            
        }
    }
}
